<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="关键词" prop="searchWord">
        <el-input
          v-model="queryParams.keyword"
          placeholder="请输入项目"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="属性" prop="searchWord">
        <el-select v-model="queryParams.special" @change="handleQuery">
          <el-option value="false" label="常规" />
          <el-option value="true" label="级联" />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['canshu:index:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-upload2"
          size="mini"
          @click="handleImport"
          v-hasPermi="['canshu:index:import']"
        >导入</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['canshu:index:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getPage"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="dataList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column align="center" label="主键" prop="id" v-if="false"/>
      <el-table-column align="left" width="100" label="类型" prop="paramCode" />
      <el-table-column align="left" width="120" label="项目" prop="paramType" />
      <el-table-column align="left" width="80" label="属性" prop="special">
        <template slot-scope="scope">{{ !scope.row.special ? '常规' : '级联' }}</template>
      </el-table-column>
      <el-table-column align="left" label="参数选项" prop="paramItem" />
      <el-table-column align="left" width="180" label="标示" prop="paramMark" />

      <el-table-column align="center" width="100" label="操作" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            v-if="!scope.row.special"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['canshu:index:edit']"
          >修改</el-button>
          <el-button
            v-if="scope.row.special"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleBelows(scope.row)"
            v-hasPermi="['canshu:index:edit']"
          >明细</el-button>
          <!--<el-button
            size="mini"
            type="text"
            icon="el-icon-status"
            @click="handleDisable(scope.row)"
            v-hasPermi="['canshu:index:edit']"
          >启用/禁用</el-button>-->
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['canshu:index:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.current"
      :limit.sync="queryParams.size"
      @pagination="getPage"
    />

    <!-- 添加或修改单表对话框 -->
    <el-dialog :title="model.title" :visible.sync="model.open" width="660px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="8">
            <el-form-item label="类型" prop="paramCode">
              <el-input v-model="form.paramCode" placeholder="小写首字母拼音"/>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="项目" prop="paramType">
              <el-input v-model="form.paramType" placeholder="选择项目名称" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="" label-width="24px" prop="special">
              <el-radio-group v-model="form.special" size="small">
                <el-radio-button :label="false">普通</el-radio-button>
                <el-radio-button :label="true">级联</el-radio-button>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <template v-if="!form.special">
            <el-col :span="24">
              <el-form-item label="参数选项" prop="paramItem">
                <el-input type="textarea" v-model="form.paramItem" placeholder="项目下若干选项，半角逗号(,)隔开" />
              </el-form-item>
            </el-col>
          </template>
          <template v-else>
            <el-col :span="4">
              <el-form-item label="级联属性"></el-form-item>
            </el-col>
            <el-col :span="20">
              <el-row v-for="(key, idx) in dictData.levels" :key="key">
                <el-col :span="10" style="margin-bottom: -9px;padding-right: 8px;">
                  <el-form-item label="" label-width="0" :prop="'paramItemCode_' + key">
                    <el-input v-model="form['paramItemCode_' + key]" :placeholder="key + '级类型'" />
                  </el-form-item>
                </el-col>
                <el-col :span="14" style="margin-bottom: -9px;">
                  <el-form-item label="" label-width="0" :prop="'paramItemType_' + key">
                    <el-input v-model="form['paramItemType_' + key]" :placeholder="key + '级项目'" />
                  </el-form-item>
                </el-col>
              </el-row>
            </el-col>
          </template>
        </el-row>
        <el-form-item label="标示" v-if="!form.special">
          <el-input v-model="form.paramMark" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog :title="belows.title" :visible.sync="belows.open" width="80%" append-to-body>
      <el-form ref="belowsForm" :model="belowsForm" label-width="80px" class="flex-container">
        <!-- 内层表格 -->
        <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleBelowAdd">添加</el-button>
        <el-table :data="belowsForm.belows" style="width: 100%">
          <template v-for="(item, idx) in belowsForm.items">
            <el-table-column :prop="item.key" :label="item.label" align="center" header-align="center"
                             :width="idx === 0 ? '150px' : ''">
              <template slot-scope="scope">
                <div style="height: 36px; line-height: 36px;">
                  <el-form-item label="" label-width="0" :prop="'belows.' + scope.$index + '.' + item.key"
                                :rules="belowRules[item.key]">
                    <el-input type="text" size="small" v-model="scope.row[item.key]"
                              :placeholder="idx === 0 ? '单个项目选项' : '多个选项则以半角逗号(,)隔开'"  />
                  </el-form-item>
                </div>
              </template>
            </el-table-column>
          </template>
          <el-table-column width="80px" align="center" header-align="center" label="操作">
            <template slot-scope="scope">
              <el-popconfirm title="确定要删除?" @confirm="() => handleBelowDel(scope.row)">
                <template #reference>
                  <a href="javascript:">删除</a>
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitBelows">确 定</el-button>
        <el-button @click="cancelBelows">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 用户导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { pageDomain, getDomain, delDomain, saveDomain, disabledDomain } from "@/api/shengchan/canshu";
import { getToken } from "@/utils/auth";
import moment from 'moment';

export default {
  name: "Canshu",
  components: {
  },
  data() {
    return {
      //按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 表格数据
      dataList: [],
      // 弹出层标题
      title: "综合参数",
      model: {
        open: false,
        title: ""
      },
      belows: {
        open: false,
        title: ""
      },
      exportUrl: "/canshu/export",
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/canshu/importData"
      },
      // 查询参数
      queryParams: {
        current: 1,
        size: 10,
        keyword: undefined
      },
      // 表单参数
      form: {},
      belowsForm: {},
      // 表单校验
      rules: {
        paramCode: [ { required: true, message: "值不能为空", trigger: "blur" } ],
        paramType: [ { required: true, message: "值不能为空", trigger: "blur" } ],
        paramItem: [ { required: true, message: "值不能为空", trigger: "blur" } ],
        paramItemCode_1: [ { required: true, message: "1级类型不能为空", trigger: "blur" } ],
        paramItemType_1: [ { required: true, message: "1级项目不能为空", trigger: "blur" } ],
      },
      belowRules: {},
      dictData: {
        levels: [1, 2, 3, 4, 5]
      }
    };
  },
  created() {
    this.getPage();
  },
  methods: {
    /** 自定义分页查询 */
    getPage() {
      this.loading = true;
      this.queryParams.params = {};
      pageDomain(this.queryParams).then(res => {
        this.dataList = res.records;
        this.total = res.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.model.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        special: false,
        status: true,
        paramCode: null,
        paramType: null,
        paramItem: null,
        paramMark: null,
        paramBelows: null,
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.current = 1;
      this.getPage();
    },
    /** 搜索按钮操作 */
    handlePage() {
      this.queryParams.current = 1;
      this.getPage();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.model.open = true;
      this.model.title = "添加" + this.title;
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.loading = true;
      this.reset();
      const id = row.id || this.ids
      if (!id) {
        this.$modal.msgError("请选中一行进行编辑");
        return
      }
      getDomain(id).then(res => {
        this.loading = false;
        if (res && res.data.special) {
          this.$modal.msgError('级联项目不允许修改')
          return
        }
        this.form = res.data;
        this.model.open = true;
        this.model.title = "修改" + this.title;
      });
    },
    handleDisable(row) {
      this.$modal.confirm("确认要禁用该项吗？").then(res => {
        console.log(res)
      });
    },
    validItem() {
      if (!this.form.special) {
        return true
      }
      const data = []
      let key = -1
      for (let i = this.dictData.levels.length; i > 1; i--) {
        if (!this.form['paramItemCode_' + i] !== !this.form['paramItemType_' + i]) {
          this.$modal.msgError(i + '级类型、项目需同时为空或非空')
          return false
        } else if (key > 0 && (!this.form['paramItemCode_' + i] || !this.form['paramItemType_' + i])) {
          this.$modal.msgError(key + '上级之' + i + '级类型、项目不能为空')
          return false
        } else if (this.form['paramItemCode_' + i]) {
          key = i
        }
        if (this.form['paramItemCode_' + i] && this.form['paramItemType_' + i]) {
          const item = {}
          item[this.form['paramItemCode_' + i]] = this.form['paramItemType_' + i]
          data.push(item)
        }
      }
      const item = {}
      item[this.form['paramItemCode_1']] = this.form['paramItemType_1']
      data.push(item)
      data.reverse()
      this.form.paramItem = JSON.stringify(data)
      return true
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid && this.validItem()) {
          this.buttonLoading = true;
          saveDomain(this.form).then(res => {
            this.$modal.msgSuccess("保存成功");
            this.model.open = false;
            this.getPage();
          }).finally(() => {
            this.buttonLoading = false;
          });
        }
      });
    },
    resetBelows() {
      this.belowsForm = {
        id: null,
        items: [],
        belows: []
      };
      this.resetForm("belowsForm");
    },
    initBelowRules(name) {
      this.belowRules = {};
      this.belowRules[name] = [ { required: true, message: '项目选项必填', trigger: 'blur' } ];
    },
    handleBelows(row) {
      this.loading = true;
      this.resetBelows();
      const id = row.id || this.ids
      if (!id) {
        this.$modal.msgError("请选中一行进行编辑");
        return
      }
      getDomain(id).then(res => {
        this.loading = false;
        this.form = res.data;
        this.belowsForm.id = this.form.id;
        this.belowsForm.items.push({ key: this.form.paramCode, label: this.form.paramType });
        this.initBelowRules(this.form.paramCode);
        const items = this.form.paramItem;
        if (items) {
          const list = JSON.parse(items);
          list.forEach(e => {
            const v = Object.entries(e);
            if (v && v.length) {
              this.belowsForm.items.push({ key: v[0][0], label: v[0][1] });
            }
          });
        }
        const belows = this.form.paramBelows;
        if (belows) {
          this.belowsForm.belows = JSON.parse(belows);
        }
        this.belows.open = true;
        this.belows.title = "修改级联-" + this.form.paramType;
      });
    },
    handleBelowAdd() {
      const belows = this.belowsForm.belows;
      const items = this.belowsForm.items;
      const newData = {};
      items.forEach(e => newData[e.key] = null );
      this.belowsForm.belows = [...belows, newData];
    },
    handleBelowDel(row) {
      const belows = [...this.belowsForm.belows];
      this.belowsForm.belows = belows.filter(item => item !== row);
    },
    submitBelows() {
      this.$refs["belowsForm"].validate(valid => {
        if (valid) {
          this.buttonLoading = true;
          const param = {
            id: this.belowsForm.id,
            paramBelows: JSON.stringify(this.belowsForm.belows)
          }
          saveDomain(param).then(res => {
            this.$modal.msgSuccess("保存成功");
            this.belows.open = false;
            this.getPage();
          }).finally(() => {
            this.buttonLoading = false;
          });
        }
      });
    },
    cancelBelows() {
      this.belows.open = false;
      this.resetBelows();
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除数据项？').then(() => {
        this.loading = true;
        return delDomain(ids);
      }).then(() => {
        this.loading = false;
        this.getPage();
        this.$modal.msgSuccess("删除成功");
      }).finally(() => {
        this.loading = false;
      });
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "用户导入";
      this.upload.open = true;
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(this.exportUrl, {
        ...this.queryParams
      }, `${this.title}_${new Date().getTime()}.xlsx`)
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(res, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(res.msg, "导入结果", { dangerouslyUseHTMLString: true });
      this.getPage();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    }
  }
};
</script>
<style scoped lang="scss">
  .flex-container .el-table .el-table__body .el-table__row {
    background-color: red;
  }
  .flex-container .el-table .el-table__cell {
    background-color: red;
  }
</style>
